<template>
    <time :datetime="datetime">{{ label }}</time>
</template>

<script setup lang="ts">
import {ref, watch} from 'vue';
import moment from "moment";
import Asserts from "@/lang/core/asserts";
import DateUtils from "@/lang/commons/date-utils";

/**
 * 国际化使用中国的
 */
moment.locale('zh-cn');

/**
 * 定义星期名称数组
 *
 * @type {string[]}
 */
const weeks = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];

/**
 * 数据日期格式转换
 *
 * 简单的文本转换，value 转换成 label
 */
interface Props {
    // 输入值
    value: number | string | Date | object;
    // 格式转换
    format?: 'datetime' | 'date' | 'time' | 'week';
    // 使用 moment 提供的接口进行转换
    pattern?: '';
}

const props = withDefaults(defineProps<Props>(), {
    value: '',
    format: undefined,
    pattern: undefined
});

const label = ref('');
const datetime = ref('');

const onchange = () => {
    const value = props.value;

    let date: Date;
    if (value instanceof Number || value instanceof String || value instanceof Date) {
        date = new Date(val);
    } else {
        // 后台 json 数据
        date = DateUtils.caseObjectToDate(value);
    }
    datetime.value = moment(date, P.datetime);

    if (props.format === undefined) {
        Asserts.notBlank(props.pattern, "format and pattern are both undefined!")
        label.value = moment(date).format(props.pattern)
    } else if (props.format === 'datetime') {
        label.value = moment(date).format(P.datetime);
    } else if (props.format === 'date') {
        label.value = moment(date).format(P.date);
    } else if (props.format === 'time') {
        label.value = moment(date).format(P.time);
    } else if (props.format === 'week') {
        // 此处可能会受到国际化影响
        label.value = weeks[date.getDay()];
    }
}

watch(() => props.value, onchange);

watch(() => props.format, onchange);

watch(() => props.pattern, onchange);

// init
onchange();
</script>